package com.ruoyi.filemanager.command;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.filemanager.constant.ElFinderConstants;
import com.ruoyi.filemanager.core.Target;
import com.ruoyi.filemanager.service.ElfinderStorage;
import com.ruoyi.filemanager.service.VolumeHandler;
import com.ruoyi.filemanager.support.archiver.Archiver;
import com.ruoyi.filemanager.support.archiver.ArchiverType;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class ArchiveCommand extends AbstractJsonCommand implements ElfinderCommand
{
    @Override
    protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json)
            throws Exception
    {
        final String[] targets = request.getParameterValues(ElFinderConstants.ELFINDER_PARAMETER_TARGETS);
        final String type = request.getParameter(ElFinderConstants.ELFINDER_PARAMETER_TYPE);

        List<Target> targetList = findTargets(elfinderStorage, targets);
        try
        {
            Archiver archiver = ArchiverType.of(type).getStrategy();
            Target targetArchive = archiver.compress(targetList.toArray(new Target[targetList.size()]));
            Object[] archiveInfos = { getTargetInfo(request, new VolumeHandler(targetArchive, elfinderStorage)) };
            json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_ADDED, archiveInfos);
        }
        catch (Exception e)
        {
            json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_ERROR, "Unable to create the archive! Error: " + e);
        }
    }
}
